<template>
  <AppLayout>
    <div
      class="bg-white dark:bg-gray-800 p-8 rounded-lg shadow-lg dark:shadow-gray-900 max-w-md mx-auto mt-20 transition-all duration-300">
      <!-- 标题和深色模式按钮 -->
      <div class="flex justify-between items-center mb-6">
        <h1 class="text-4xl font-bold text-blue-900 dark:text-blue-300">注册账号</h1>
        <button @click="goBack"
          class="w-10 h-10 flex items-center justify-center rounded-full bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-100 hover:bg-gray-300 dark:hover:bg-gray-600">
          <div class="i-mdi-arrow-left"></div>
        </button>
        <button @click="themeStore.toggleTheme"
          class="w-10 h-10 flex items-center justify-center rounded-full bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-100 hover:bg-gray-300 dark:hover:bg-gray-600 transition-colors">
          <i :class="themeStore.isDarkTheme ? 'i-mdi-white-balance-sunny' : 'i-mdi-moon-waxing-crescent'"></i>
        </button>
      </div>

      <!-- 错误提示 -->
      <div v-if="error"
        class="bg-red-50 dark:bg-red-900 border border-red-200 dark:border-red-700 text-red-700 dark:text-red-300 p-4 rounded-lg mb-6">
        <i class="i-mdi-alert-circle mr-2"></i>
        <span>{{ error }}</span>
      </div>

      <form @submit.prevent="handleRegister" class="space-y-6">
        <!-- 用户名输入 -->
        <div class="relative">
          <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
            <i class="i-mdi-account text-gray-400 dark:text-gray-500"></i>
          </div>
          <input v-model="form.username" type="text" placeholder="用户名，建议使用邮箱"
            class="w-full pl-10 pr-3 py-3 border-2 border-gray-200 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200 focus:border-blue-500 dark:focus:border-blue-400 rounded-lg focus:outline-none transition duration-300">
        </div>

        <!-- 邮箱输入 -->
        <div class="relative">
          <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
            <i class="i-mdi-email text-gray-400 dark:text-gray-500"></i>
          </div>
          <input v-model="form.email" type="email" placeholder="邮箱地址"
            class="w-full pl-10 pr-3 py-3 border-2 border-gray-200 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200 focus:border-blue-500 dark:focus:border-blue-400 rounded-lg focus:outline-none transition duration-300">
        </div>

        <!-- 邮箱验证码组件 -->
        <div class="relative">
          <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
            <i class="i-mdi-key text-gray-400 dark:text-gray-500"></i>
          </div>
          <input v-model="form.code" type="text" placeholder="邮箱验证码"
            class="w-full pl-10 pr-16 py-3 border-2 border-gray-200 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200 focus:border-blue-500 dark:focus:border-blue-400 rounded-lg focus:outline-none transition duration-300"
            :class="codeError ? 'border-red-500 dark:border-red-400' : ''">
          <button @click="sendCode" :disabled="sending || countDown > 0"
            class="absolute inset-y-0 right-0 pr-3 flex items-center bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 px-3 py-1 rounded-lg text-sm hover:bg-gray-300 dark:hover:bg-gray-600 transition duration-300">
            {{ countDown > 0 ? `${countDown}s` : sending ? '发送中...' : '发送验证码' }}
          </button>
        </div>

        <!-- 密码输入 -->
        <div class="relative">
          <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
            <i class="i-mdi-lock text-gray-400 dark:text-gray-500"></i>
          </div>
          <input v-model="form.password" type="password" placeholder="密码 (至少6位)"
            class="w-full pl-10 pr-3 py-3 border-2 border-gray-200 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200 focus:border-blue-500 dark:focus:border-blue-400 rounded-lg focus:outline-none transition duration-300">
        </div>

        <!-- 确认密码输入 -->
        <div class="relative">
          <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
            <i class="i-mdi-lock text-gray-400 dark:text-gray-500"></i>
          </div>
          <input v-model="form.confirmPassword" type="password" placeholder="确认密码"
            class="w-full pl-10 pr-3 py-3 border-2 border-gray-200 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200 focus:border-blue-500 dark:focus:border-blue-400 rounded-lg focus:outline-none transition duration-300"
            :class="{
              'border-red-500 dark:border-red-400': form.confirmPassword !== form.password && form.confirmPassword
            }">
          <div v-if="form.confirmPassword !== form.password && form.confirmPassword"
            class="absolute inset-y-0 right-0 pr-3 flex items-center text-red-500 dark:text-red-400">
            <i class="i-mdi-close"></i>
          </div>
        </div>

        <!-- 注册按钮（与登录按钮风格一致） -->
        <button type="button" @click="handleRegister" :disabled="loading"
          class="w-full bg-blue-500 dark:bg-blue-400 text-white dark:text-gray-900 font-semibold py-3 rounded-lg hover:bg-blue-600 dark:hover:bg-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400 transition duration-300">
          {{ loading ? '注册中...' : '注册账号' }}
        </button>
      </form>

      <!-- 登录链接 -->
      <div class="mt-6 text-center text-sm text-gray-500 dark:text-gray-400">
        <p>
          已有账号?
          <router-link to="/login"
            class="text-blue-600 dark:text-blue-400 hover:underline transition-colors">立即登录</router-link>
        </p>
      </div>
    </div>

  </AppLayout>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useThemeStore } from '@/stores/themeStore';
import AppLayout from '@/components/AppLayout.vue';
import { useRouter } from 'vue-router'

import { api } from '@/api'

const themeStore = useThemeStore();
const loading = ref(false);
const error = ref('');
const router = useRouter();
const codeError = ref(false);
const sending = ref(false);
const countDown = ref(0);
let countdownTimer: number | null = null;
// 注册返回到登录
const goBack = () => {
  router.push('/login')
}

// 表单数据
const form = reactive({
  username: '',
  email: '',
  code: '',
  password: '',
  confirmPassword: ''
});

// 发送验证码
const sendCode = async () => {
  if (sending.value || countDown.value > 0) return;
  if (!form.email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) {
    error.value = '请输入有效的邮箱地址';
    codeError.value = true;
    return;
  }

  codeError.value = false;
  sending.value = true;
  error.value = '';

  try {
    console.log("前端获取到的email: ", form.email);
    await api.sendEmail(form.email);
    startCountdown();
    error.value = '验证码已发送，请查收邮箱';
  } catch (err: any) {
    error.value = err.response?.data?.message || '发送验证码失败，请稍后再试';
  } finally {
    sending.value = false;
  }
};
// 倒计时功能
const startCountdown = () => {
  countDown.value = 60;
  countdownTimer = window.setInterval(() => {
    countDown.value--;
    if (countDown.value <= 0) {
      window.clearInterval(countdownTimer as number);
      countdownTimer = null;
    }
  }, 1000);
};

// 表单验证
const validateForm = () => {
  let errors = '';
  if (!form.username) {
    errors += '请输入用户名\n';
  }
  if (!form.email) {
    errors += '请输入邮箱\n';
  } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) {
    errors += '请输入有效的邮箱地址\n';
  }
  if (!form.password) {
    errors += '请输入密码\n';
  } else if (form.password.length < 6) {
    errors += '密码至少需要6个字符\n';
  }
  if (!form.confirmPassword) {
    errors += '请确认密码\n';
  } else if (form.confirmPassword !== form.password) {
    errors += '两次输入的密码不一致\n';
  }
  return errors;
};

// 点击注册按钮处理注册
const handleRegister = async () => {
  if (loading.value || !form.code || !form.password) return;

  const formErrors = validateForm();
  if (formErrors) {
    error.value = formErrors;
    return;
  }

  loading.value = true;
  error.value = '';

  try {
    // @ts-ignore 
    const response = await api.registerWithEmail(form.email, form.code, form.password);
    // todo: 存储token?
    // 注册成功后存储令牌并跳转
    // localStorage.setItem('token', response.token);
    router.push('/');
  } catch (err: any) {
      error.value =  "注册失败,该邮箱可能已被注册 ";
  } finally {
    loading.value = false;
  }
};

// 应用主题
onMounted(() => {
  themeStore.applyTheme();
});

</script>